package com.example.demo.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.metadata.OrderItem;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.demo.dto.OkDTO;
import com.example.demo.dto.PageDTO;
import com.example.demo.mapper.ElderlyBasicOkMapper;
import com.example.demo.pojo.ElderlyBasic;
import com.example.demo.pojo.ElderlyBasicOk;
import com.example.demo.pojo.ElderlyDetailed;
import com.example.demo.pojo.ElderlyDetailedOk;
import com.example.demo.service.ElderlyBasicOkService;
import com.example.demo.service.ElderlyBasicService;
import com.example.demo.service.ElderlyDetailedOkService;
import com.example.demo.service.ElderlyDetailedService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
public class ElderlyBasicOkServiceImpl extends ServiceImpl<ElderlyBasicOkMapper, ElderlyBasicOk> implements ElderlyBasicOkService {
    @Autowired
    private ElderlyBasicService elderlyBasicService;
    @Autowired
    private ElderlyDetailedService elderlyDetailedService;
    @Autowired
    private ElderlyDetailedOkService elderlyDetailedOkService;
    @Override
    @Transactional
    public void ok(OkDTO elderlyOkDTO) {
        Boolean ok = elderlyOkDTO.getOk();
        Long id = elderlyOkDTO.getId();

        // 拷贝到另一个数据库
        if (ok) {
            ElderlyBasic elderlyBasic = elderlyBasicService.getById(id);
            ElderlyBasicOk elderlyBasicOk = BeanUtil.copyProperties(elderlyBasic, ElderlyBasicOk.class);
            save(elderlyBasicOk);

            List<ElderlyDetailed> elderlyDetailedList = elderlyDetailedService.lambdaQuery().eq(ElderlyDetailed::getElderlyId, id).list();
            List<ElderlyDetailedOk> elderlyDetailedOkList = BeanUtil.copyToList(elderlyDetailedList, ElderlyDetailedOk.class);
            elderlyDetailedOkService.saveBatch(elderlyDetailedOkList);

        }

        // 删除原来数据库的内容
        elderlyBasicService.removeById(id);
        elderlyDetailedService.lambdaUpdate()
                .eq(ElderlyDetailed::getElderlyId, id)
                .remove();
    }

    @Override
    public List<ElderlyBasicOk> getElderlyBasicOk(PageDTO pageDTO) {
        Integer page = pageDTO.getPage();
        Integer pageSize = pageDTO.getPageSize();
        String sortFiled = pageDTO.getSortFiled();

        Page<ElderlyBasicOk> p = Page.of(page, pageSize);
        p.addOrder(new OrderItem("id", false));
        lambdaQuery().page(p);

        return p.getRecords();
    }
}
